package com.hand.wfive.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;

import androidx.exifinterface.media.ExifInterface;

import com.doris.media.picker.utils.MediaUtils;
import com.hand.wfive.App;
import com.hand.wfive.R;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.RectangleReadOnly;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

public class ImageUtils {

    private static final String TAG = ImageUtils.class.getSimpleName();

    /**
     * 保存Bitmap为图片PNG，返回图片路径
     */
    public static String saveBitmapPNG(Context context, Bitmap bitmap, String path) {
        return saveBitmap(context, bitmap, Bitmap.CompressFormat.PNG,
                path, getPngName(), 100);
    }

    public static String saveBitmapPNG(Context context, Bitmap bitmap, String path, String name) {
        return saveBitmap(context, bitmap, Bitmap.CompressFormat.PNG,
                path, name, 100);
    }

    public static String getPngName() {
        return "IMG_" + FileUtils.getRandomFileName() + ".png";
    }

    /**
     * 保存Bitmap为图片JPG，返回图片路径
     */
    public static String saveBitmapJPG(Context context, Bitmap bitmap) {
        return saveBitmapJPG(context, bitmap, App.getContext().getImgPath());
    }

    public static String saveBitmapJPG(Context context, Bitmap bitmap, String path) {
        return saveBitmapJPG(context, bitmap, path, getJpgName());
    }

    public static String saveBitmapJPG(Context context, Bitmap bitmap, String path, String name) {
        return saveBitmap(context, bitmap, Bitmap.CompressFormat.JPEG,
                path, name, 100);
    }

    public static String saveBitmapJPG_AllPath(Context context, Bitmap bitmap, String allPath) {
        int lastS = allPath.lastIndexOf("/");
        return saveBitmapJPG(context, bitmap, allPath.substring(0, lastS),
                allPath.substring(lastS + 1));
    }

    public static String getJpgName() {
        return "IMG_" + FileUtils.getRandomFileName() + ".jpg";
    }

    /**
     * 保存Bitmap为图片，返回图片路径
     */
    public static String saveBitmap(
            Context context, Bitmap bitmap, Bitmap.CompressFormat format,
            String parentPath, String fileName, int quality) {
        File file = new File(parentPath, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(format, quality, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String path = file.getAbsolutePath();
        MediaUtils.refreshSystemMedia(context, path);
        logD("saveBitmap(): ", path);
        return path;
    }

    /**
     * 加载本地图片
     *
     * @return Bitmap
     */
    public static Bitmap loadLocalImage(String path) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        try {
            Matrix matrix = new Matrix();
            matrix.postRotate(ImageUtils.readPictureDegree(path));
            return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                    matrix, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 绘制已经测量过的View（Bitmap）
     */
    public static Bitmap getViewBitmap(View view) {
        int width = view.getWidth();
        int height = view.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }

    /**
     * 绘制WebView指定宽高（Bitmap）
     */
    public static Bitmap getWebViewBitmap(WebView webView, int width, int height) {
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        webView.draw(canvas);
        return bitmap;
    }

    /**
     * 添加水印
     */
    public static Bitmap addWatermark(Bitmap bitmap) {
        try {
            Bitmap originalWatermark = BitmapFactory.decodeResource(
                    App.getContext().getResources(), R.mipmap.ic_sign_watermark);
            float scale = bitmap.getWidth() * 1f / originalWatermark.getWidth();
            Matrix matrix = new Matrix();
            matrix.setScale(scale, scale);
            Bitmap scaleWatermark = Bitmap.createBitmap(originalWatermark, 0, 0,
                    originalWatermark.getWidth(), originalWatermark.getHeight(), matrix, true);
            Bitmap cropWatermark;
            if (scaleWatermark.getHeight() >= bitmap.getHeight()) {
                cropWatermark = Bitmap.createBitmap(scaleWatermark, 0,
                        (scaleWatermark.getHeight() - bitmap.getHeight()) / 2,
                        bitmap.getWidth(), bitmap.getHeight(), null, true);
            } else {
                scale = bitmap.getHeight() * 1f / originalWatermark.getHeight();
                matrix.reset();
                matrix.setScale(scale, scale);
                scaleWatermark = Bitmap.createBitmap(originalWatermark, 0, 0,
                        originalWatermark.getWidth(), originalWatermark.getHeight(), matrix, true);
                cropWatermark = Bitmap.createBitmap(
                        scaleWatermark, (scaleWatermark.getWidth() - bitmap.getWidth()) / 2, 0,
                        bitmap.getWidth(), bitmap.getHeight(), null, true);
            }
            Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
                    Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(newBitmap);
            canvas.drawBitmap(bitmap, 0f, 0f, null);
            canvas.drawBitmap(cropWatermark, 0f, 0f, null);
            canvas.save();
            canvas.restore();
            return newBitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 获取图片旋转角度
     */
    public static int readPictureDegree(String srcPath) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(srcPath);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * Base64编码的字符串 转 Bitmap
     */
    public static Bitmap toBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    /**
     * 旋转保存到原路径
     */
    public static boolean rotateToPath(String filePath, int degrees) {
        try {
            Bitmap bitmap = loadLocalImage(filePath);
            bitmap = rotateBitmap(bitmap, degrees);
            if (bitmap == null || filePath == null) {
                return false;
            }
            FileOutputStream fos = new FileOutputStream(filePath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private static Bitmap rotateBitmap(Bitmap bitmap, int rotate) {
        if (bitmap == null) {
            return null;
        } else {
            int w = bitmap.getWidth();
            int h = bitmap.getHeight();
            Matrix matrix = new Matrix();
            matrix.postRotate((float) rotate);
            return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
        }
    }

    /**
     * 生成PDF
     *
     * @param data   图片路径集合
     * @param path   保存目录
     * @param name   包名名称（含后缀）
     * @param width  PDF页面宽
     * @param height PDF页面高
     */
    public static String savePDF(
            ArrayList<String> data, String path, String name, int width, int height) {
        Document doc = new Document(new RectangleReadOnly(width, height),
                0, 0, 0, 0);
        File file = new File(path, name);
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            PdfWriter.getInstance(doc, outputStream);
            doc.open();
            for (String item : data) {
                doc.newPage();
                Bitmap bitmap = BitmapFactory.decodeFile(item);
                Image image = Image.getInstance(item);
                image.setAlignment(Image.MIDDLE);
                image.scalePercent(Math.round(width * 1f / bitmap.getWidth() * 100));
                bitmap.recycle();
                doc.add(image);
            }
            doc.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file.getAbsolutePath();
    }


    public static Bitmap getBitmapFromFile(File dst) {
        return getBitmapFromFile(dst ,false);
    }

    /**
     * 从文件读取Bitmap
     *
     * @param dst                目标路径
     * @param processOrientation 是否处理图片旋转角度
     * @return
     */
    public static Bitmap getBitmapFromFile(File dst, boolean processOrientation) {
        if (null != dst && dst.exists()) {
            try {
                Bitmap bitmap = BitmapFactory.decodeFile(dst.getPath());
                if (!processOrientation) {
                    return bitmap;
                }
                int orientation = readPictureDegree(dst.getPath());
                if (orientation == 0) {
                    return bitmap;
                } else {
                    Matrix matrix = new Matrix();
                    matrix.postRotate(orientation);
                    return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                }
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private static void logD(String... msgs) {
        StringBuilder sb = new StringBuilder();
        if (msgs != null && msgs.length > 0) {
            for (String item : msgs) {
                sb.append(item);
            }
        }
        Log.d(TAG, sb.toString());
    }
}
